package com.wechat.page.chat.message.msg;

import java.util.List;

import com.swak.fx.support.ability.DragAbleAbility;
import com.swak.fx.support.ui.UIImage;
import com.swak.fx.support.ui.UILifecycle;
import com.wechat.dto.MessageDTO;
import com.wechat.face.Face;
import com.wechat.face.Faces;

import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.scene.Node;
import javafx.scene.text.Text;
import javafx.scene.text.TextAlignment;
import javafx.scene.text.TextFlow;

/**
 * 文本消息
 * 
 * @author 618lf
 */
public class TextMsgComp extends AbstractMsgComp implements MsgComp, UILifecycle {

	private final String STYLE_CLASS = "message__text";
	private final String ARROWS_STYLE_CLASS = "message__text-arrows";
	private final String INNER_STYLE_CLASS = "message__text-inner";
	private final String TEXT_STYLE_CLASS = "message__text-text";

	private TextFlow textPane;

	public TextMsgComp(MessageDTO message) {
		super(message);
		this.textPane = new TextFlow();
		this.init();
	}

	@Override
	public void initializeParts() {
		super.initializeParts();
		this.getStyleClass().add(STYLE_CLASS);
		this.arrows.getStyleClass().add(ARROWS_STYLE_CLASS);
		this.textPane.getStyleClass().add(INNER_STYLE_CLASS);
		this.setMaxWidth(Max_Width);
		this.textPane.setMaxWidth(Max_Width);
		this.textPane.setLineSpacing(4);
		this.textPane.setTextAlignment(TextAlignment.JUSTIFY);
	}

	@Override
	public void setupValueChangedListeners() {
		super.setupValueChangedListeners();
		this.prefHeightProperty().bind(this.textPane.heightProperty());
		this.textProperty.addListener((ob, o, n) -> {
			List<Object> texts = Faces.parseString(n);
			for (Object text : texts) {
				if (text instanceof String) {
					this.textPane.getChildren().add(this.buildText((String) text));
				} else if (text instanceof Face) {
					this.textPane.getChildren().add(this.buildImage((Face) text));
				}
			}
		});
	}

	private Text buildText(String text) {
		Text textNode = new Text();
		textNode.setText(text);
		textNode.getStyleClass().add(TEXT_STYLE_CLASS);
		textNode.setTextAlignment(TextAlignment.JUSTIFY);
		return textNode;
	}

	private Node buildImage(Face face) {
		UIImage image = new UIImage();
		image.setPrefSize(face.getWidth(), face.getHeight());
		image.image(face.getRealPath());
		image.getStyleClass().add(TEXT_STYLE_CLASS);
		return image;
	}

	@Override
	public void initializeFinish() {
		super.initializeFinish();
		this.textProperty.set(message.getMsgContent());

		// 添加可移动的能力
		new DragAbleAbility(this.textPane, () -> message);
	}

	@Override
	protected Node getContentNode() {
		return this.textPane;
	}

	private final StringProperty textProperty = new SimpleStringProperty();
}